package uestc.lj.gulishop.seckill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import uestc.lj.common.utils.R;
import uestc.lj.gulishop.seckill.service.SeckillService;
import uestc.lj.gulishop.seckill.to.SeckillSkuRedisTO;

import java.util.List;

/**
 * @Author:Crazlee
 * @Date:2021/6/23
 */
@Controller
public class SeckillController {

    @Autowired
    private SeckillService seckillService;

    /**
     * 返回当前时间可以参与的秒杀商品信息
     *
     * @return
     */
    @GetMapping("/current/seckill/skus")
    @ResponseBody
    public R getCurrentSeckillSkus() {
        List<SeckillSkuRedisTO> seckillSkuRedisTOList = seckillService.getCurrentSeckillSkus();
        return R.ok().setData(seckillSkuRedisTOList);
    }

    /**
     * 获取当前skuId商品所涉及的所有秒杀场次的秒杀信息
     *
     * @param skuId
     * @return
     */
    @GetMapping("/sku/seckill/{skuId}")
    @ResponseBody
    public R getSkuSeckillInfo(@PathVariable("skuId") Long skuId) {
        List<SeckillSkuRedisTO> seckillSkuRedisTOList = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(seckillSkuRedisTOList);
    }

    /**
     * 秒杀加入购物车，处理秒杀抢购逻辑
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @GetMapping("/kill")
    public String secKill(@RequestParam("killId") String killId,
                          @RequestParam("key") String key,
                          @RequestParam("num") Integer num,
                          Model model) {
        // 1.后台判断是否登录，限流

        // 2.执行秒杀逻辑
        String orderSn = seckillService.kill(killId, key, num);
        model.addAttribute("orderSn", orderSn);
        return "success";
    }

}
